package com.sxt.client;

import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class TCPClient extends JFrame {
    private static final long serialVersionUID = 1L;
    private static String str = "";
    private static PrintWriter pw = null;
    private static Socket s = null;
    private static StringBuffer stringBuffer = new StringBuffer();
    private static BufferedReader br = null;
    private static JTextArea textArea = null;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new TCPClient();

        try {
	  s = new Socket("localhost", 8888);
	  System.out.println("服务器已连接...");
	  pw = new PrintWriter(s.getOutputStream());
	  br = new BufferedReader(new InputStreamReader(s.getInputStream()));
	  while ((str = br.readLine()) != null) {
	      stringBuffer.append(str + "\n");
	      textArea.setText(stringBuffer.toString());
	  }

        } catch (ConnectException e) {
	  System.out.println("服务器未响应！");
        } catch (UnknownHostException e) {
	  // TODO Auto-generated catch block
	  System.out.println("找不服务器！");
        } catch (IOException e) {
	  // TODO Auto-generated catch block
	  System.out.println("连接失败！");
        }
    }

    /**
     * 构造方法，用于界面处理
     */
    public TCPClient() {
        this.setTitle("聊天客户端");
        this.setSize(300, 300);
        this.setLocation(300, 200);
        this.setVisible(true);
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        final JTextField textField = new JTextField(20);
        textArea = new JTextArea(10, 20);
        panel.add(textArea, BorderLayout.NORTH);
        panel.add(textField, BorderLayout.SOUTH);
        add(panel);
        this.pack();

        /**
         * 监听键盘事件，如果是回车，将TextFied的内容发送到服务器，并送到TextArea
         */
        textField.addKeyListener(new KeyAdapter() {
	  @Override
	  public void keyTyped(KeyEvent e) {
	      // TODO Auto-generated method stub
	      super.keyTyped(e);
	      char c = e.getKeyChar();

	      if (c == KeyEvent.VK_ENTER) {
		str.trim();
		str = textField.getText();
		pw.println(str);
		pw.flush();
		c = 0;
		textField.setText("");
	      }
	  }
        });
    }
}
